import re
from metagpt.actions import Action
from metagpt.logs import logger
import time
from datetime import datetime
import requests

class CommentCode(Action):
    #! Take as input a C/C++ code and return a line by line comment of the input C/C++ code. Write the commented code to a file named `main.cpp`.
    
    name: str = "CommentCode"
    
    ROLE_DESCRIPTION: str = """In this team, you are an expert in coding C/C++ programs and required to give a line by line comment of the input C/C++ code. You should not change the code, but provide a detailed explanation of each line. This will help the Rust translator to understand the code better and make the translation process more accurate. Response with ```cpp \n your_code_here \n ``` with NO other texts. """
    
    PROMPT_TEMPLATE: str = """{TEAM_DESCRIPTION}\n{ROLE_DESCRIPTION}
    ## Input
    {input_code}
    ## Your Output
    """
        
    async def run(self, team_desc: str, input_code: str):
        prompt = self.PROMPT_TEMPLATE.format(TEAM_DESCRIPTION=team_desc, ROLE_DESCRIPTION=self.ROLE_DESCRIPTION, input_code=input_code)
        rsp = await self._aask(prompt)
        code_text = CommentCode.parse_code(rsp)
        timestamp = time.time()
        # 将秒数转换为日期和时间
        dt_object = datetime.fromtimestamp(timestamp)
        # 将日期和时间转换为字符串
        human_readable_time = dt_object.strftime("%Y-%m-%d %H:%M:%S")
        data = {"time": human_readable_time,"compare":timestamp,"sender":"commenter","receiver":"translater","content":code_text}
        response = requests.post("http://localhost:5400/post_msg",json=data)
        response_data = response.json()
        print(response_data)
        with open("main.cpp", "w") as f:
            f.write(code_text)
        return "main.cpp"
    
    @staticmethod
    def parse_code(rsp):
        pattern = r"```cpp(.*)```"
        match = re.search(pattern, rsp, re.DOTALL)
        code_text = match.group(1) if match else rsp
        return code_text
